package com.xuelangyun.form.common.exception;

import com.xuelangyun.form.common.utils.R;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理器
 *
 * @author weiqing.hk
 * @version 1.0
 * @date 2024年06月17日 下午10:16:19
 */
@RestControllerAdvice
public class DyformExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(NoHandlerFoundException.class)
    public R<Object> handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.error(404, "路径不存在，请检查路径是否正确");
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(DyformException.class)
    public R<Object> handleRRException(DyformException e) {
        R<Object> r = new R<Object>();
        r.setCode(e.getCode());
        r.setMsg(e.getMessage());
        return r;
    }


    @ExceptionHandler(DuplicateKeyException.class)
    public R<Object> handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return R.error("数据库中已存在该记录");
    }

    @ExceptionHandler(Exception.class)
    public R<Object> handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.error();
    }

    @ExceptionHandler(AuthorizationException.class)
    public R<Object> handleAuthorizationException(AuthorizationException e) {
        logger.error(e.getMessage(), e);
        return R.error("当前用户没有此操作的权限!");
    }


}
